package com.region.loadbalancer.policy;

import com.region.loadbalancer.group.Server;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Polling Scheduling Policy
 *
 * @author liujieyu
 * @date 2023/5/25 23:49
 * @desciption
 */
public class RoundRobinPolicy implements BalancerPolicy{

    AtomicInteger count = new AtomicInteger(0);

    @Override
    public Server choose(List<Server> servers) {
        int length = servers.size();
        if (count.get() > Integer.MAX_VALUE >> 1 && count.get() % length == 0) {
            count.set(0);
        }
        return servers.get(count.getAndIncrement() % length);
    }

    @Override
    public BalancerPolicy deepClone() {
        return new RoundRobinPolicy();
    }
}
